package com.saicent.note.service.impl;

import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.StringJoiner;

import org.springframework.stereotype.Service;

import com.saicent.note.core.Article;
import com.saicent.note.service.JspFileArticleService;
import com.saicent.support.service.ServiceException;
import com.saicent.support.service.ServiceSupport;
import com.saicent.support.utils.IOUtils;

@Service
public class JspFileArticleServiceImpl extends ServiceSupport implements JspFileArticleService {

	private String jspFileDirectory;
	
	public String getJspFileDirectory() {
		return jspFileDirectory;
	}

	@Override
	public void setJspFileDirectory(String jspFileDirectory) {
		this.jspFileDirectory = jspFileDirectory;
	}
	
	@Override
	public void createArticle(Article article) throws ServiceException {
		
		String jspFilename = nextJspFilename();
		Path path = Paths.get(jspFileDirectory, jspFilename);
		StringJoiner categoriesJoiner = new StringJoiner(",");
		for (String category : article.getCategories()) {
			categoriesJoiner.add(category);
		}
		String categories = categoriesJoiner.toString();
		try (PrintStream printStream = new PrintStream(path.toFile(), "UTF8")) {
			printStream.println("<%@ page language=\"java\" contentType=\"text/html; charset=UTF8\" pageEncoding=\"UTF8\"%>");
			printStream.println("<!DOCTYPE html>");
			printStream.println("<html>");
			printStream.println("<head>");
			printStream.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf8\">");
			printStream.println("<meta name=\"categories\" content=\"" + categories + "\">");
			printStream.println("<title>" + article.getTitle() + "</title>");
			printStream.println("</head>");
			printStream.println("<body>");
			printStream.println(article.getContent());
			printStream.println("</body>");
			printStream.println("</html>");
			printStream.flush();
			printStream.close();
		} catch (Exception e) {
			throw new ServiceException(e.getMessage(), e);
		}
		
	}
	
	private String nextJspFilename() {
		int index = 1;
		for (;;) {
			String jspFilename = IOUtils.completeFilename("thread-" + (index++), IOUtils.EXTENSION_JSP);
			Path path = Paths.get(jspFileDirectory, jspFilename);
			File file = path.toFile();
			if (!file.exists()) {
				return jspFilename;
			}
 		}
	}

	@Override
	public void createArticle(InputStream inputStream) {
		// TODO Auto-generated method stub
		
	}

}
